package com.study.quiz.config;

import com.study.quiz.pojo.User;
import com.study.quiz.service.NotifictionService;
import com.study.quiz.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author CJunGod
 * @create 2020-03-06 21:01
 **/
@Component
public class SessionInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private NotifictionService notifictionService;

    @Value("${token}")
    private String userToken;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals(userToken)) {
                    User byToken = userService.findByToken(c.getValue());
                    if (byToken != null) {
                        Long unreadCount = notifictionService.unreadCount(byToken.getId());
                        request.getSession().setAttribute("user", byToken);
                        request.getSession().setAttribute("unReadCount",unreadCount);
                        request.getSession().setMaxInactiveInterval(600);
                        break;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (response.getStatus() == 500) {
            modelAndView.getModelMap().put("errorCode", response.getStatus() + "程序处理异常");
            modelAndView.getModelMap().put("errorMsg", "哇偶，您的访问异常，请联系管理员");
            modelAndView.setViewName("/common/error");
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
